import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import json
import os
from datetime import datetime, timedelta
from typing import Callable, List, Dict
import re


class HistoryTab:
    """历史记录界面标签页"""
    
    def __init__(self, parent_frame):
        self.parent_frame = parent_frame
        
        # 控件
        self.history_tree = None
        self.history_display = None
        self.search_var = None
        self.search_entry = None
        
        # 回调函数
        self.on_load_conversation = None
        self.on_delete_conversation = None
        
        # 数据
        self.history_data = []
        self.filtered_data = []
        
        self.setup_history_interface()
    
    def setup_history_interface(self):
        """设置历史记录界面"""
        # 创建主框架
        main_frame = ttk.Frame(self.parent_frame)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 左侧：历史记录列表
        left_frame = ttk.Frame(main_frame)
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 标题和搜索框
        header_frame = ttk.Frame(left_frame)
        header_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(header_frame, text="📚 历史对话", font=('TkDefaultFont', 12, 'bold')).pack(side=tk.LEFT)
        
        # 搜索框
        search_frame = ttk.Frame(header_frame)
        search_frame.pack(side=tk.RIGHT)
        
        ttk.Label(search_frame, text="🔍").pack(side=tk.LEFT, padx=(0, 5))
        self.search_var = tk.StringVar()
        self.search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=20)
        self.search_entry.pack(side=tk.LEFT)
        self.search_var.trace('w', self._on_search_change)
        
        # 创建Treeview显示历史记录
        tree_frame = ttk.Frame(left_frame)
        tree_frame.pack(fill=tk.BOTH, expand=True)
        
        columns = ('time', 'title', 'messages', 'duration')
        self.history_tree = ttk.Treeview(tree_frame, columns=columns, show='headings', height=15)
        
        # 设置列标题和宽度
        self.history_tree.heading('time', text='📅 时间')
        self.history_tree.heading('title', text='💬 标题')
        self.history_tree.heading('messages', text='📝 消息数')
        self.history_tree.heading('duration', text='⏱️ 时长')
        
        self.history_tree.column('time', width=140, minwidth=120)
        self.history_tree.column('title', width=220, minwidth=150)
        self.history_tree.column('messages', width=70, minwidth=60)
        self.history_tree.column('duration', width=80, minwidth=60)
        
        # 添加滚动条
        tree_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=self.history_tree.yview)
        self.history_tree.configure(yscrollcommand=tree_scrollbar.set)
        
        self.history_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tree_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 绑定事件
        self.history_tree.bind('<<TreeviewSelect>>', self._on_history_select)
        self.history_tree.bind('<Double-1>', self._on_double_click)
        
        # 按钮框架
        button_frame = ttk.Frame(left_frame)
        button_frame.pack(fill=tk.X, pady=(10, 0))
        
        # 使用图标和更好的按钮样式
        ttk.Button(button_frame, text="📂 加载对话", command=self._on_load_click).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(button_frame, text="🗑️ 删除对话", command=self._on_delete_click).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(button_frame, text="🔄 刷新列表", command=self.refresh_history).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(button_frame, text="🧹 清空搜索", command=self._clear_search).pack(side=tk.LEFT)
        
        # 分隔符
        separator = ttk.Separator(main_frame, orient=tk.VERTICAL)
        separator.pack(side=tk.LEFT, fill=tk.Y, padx=15)
        
        # 右侧：对话内容预览
        right_frame = ttk.Frame(main_frame)
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 预览标题
        preview_header = ttk.Frame(right_frame)
        preview_header.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(preview_header, text="👁️ 对话预览", font=('TkDefaultFont', 12, 'bold')).pack(side=tk.LEFT)
        
        # 统计信息
        self.stats_label = ttk.Label(preview_header, text="", font=('TkDefaultFont', 9))
        self.stats_label.pack(side=tk.RIGHT)
        
        # 对话内容显示区域
        display_frame = ttk.Frame(right_frame)
        display_frame.pack(fill=tk.BOTH, expand=True)
        
        self.history_display = scrolledtext.ScrolledText(
            display_frame,
            wrap=tk.WORD,
            font=('Microsoft YaHei UI', 10),
            state=tk.DISABLED,
            height=20,
            bg='#FAFAFA',
            relief=tk.FLAT,
            borderwidth=1
        )
        self.history_display.pack(fill=tk.BOTH, expand=True)
        
        # 配置文本样式
        self.setup_display_styles()
        
        # 初始加载历史记录
        self.refresh_history()
    
    def setup_display_styles(self):
        """设置显示样式"""
        if not self.history_display:
            return
        
        # 用户消息样式 - 绿色主题
        self.history_display.tag_configure("user_header", 
                                         foreground="#FFFFFF", 
                                         background="#4CAF50",
                                         font=('Microsoft YaHei UI', 10, 'bold'),
                                         relief=tk.RAISED,
                                         borderwidth=1)
        
        self.history_display.tag_configure("user_content", 
                                         foreground="#2E7D32", 
                                         background="#E8F5E8",
                                         font=('Microsoft YaHei UI', 10),
                                         lmargin1=20, lmargin2=20, rmargin=20,
                                         spacing1=5, spacing3=5)
        
        # AI消息样式 - 蓝色主题
        self.history_display.tag_configure("ai_header", 
                                         foreground="#FFFFFF", 
                                         background="#2196F3",
                                         font=('Microsoft YaHei UI', 10, 'bold'),
                                         relief=tk.RAISED,
                                         borderwidth=1)
        
        self.history_display.tag_configure("ai_content", 
                                         foreground="#1565C0", 
                                         background="#E3F2FD",
                                         font=('Microsoft YaHei UI', 10),
                                         lmargin1=20, lmargin2=20, rmargin=20,
                                         spacing1=5, spacing3=5)
        
        # 系统消息样式 - 橙色主题
        self.history_display.tag_configure("system_header", 
                                         foreground="#FFFFFF", 
                                         background="#FF9800",
                                         font=('Microsoft YaHei UI', 10, 'bold'),
                                         relief=tk.RAISED,
                                         borderwidth=1)
        
        self.history_display.tag_configure("system_content", 
                                         foreground="#F57C00", 
                                         background="#FFF3E0",
                                         font=('Microsoft YaHei UI', 10, 'italic'),
                                         lmargin1=20, lmargin2=20, rmargin=20,
                                         spacing1=5, spacing3=5)
        
        # 时间戳样式
        self.history_display.tag_configure("timestamp", 
                                         foreground="#9E9E9E", 
                                         font=('Microsoft YaHei UI', 8),
                                         justify=tk.CENTER)
        
        # 分隔线样式
        self.history_display.tag_configure("separator", 
                                         foreground="#E0E0E0",
                                         justify=tk.CENTER,
                                         spacing1=10, spacing3=10)
        
        # 思考过程样式
        self.history_display.tag_configure("thinking_header",
                                         foreground="#FFFFFF",
                                         background="#9C27B0",
                                         font=('Microsoft YaHei UI', 9, 'bold'))
        
        self.history_display.tag_configure("thinking_content",
                                         foreground="#7B1FA2",
                                         background="#F3E5F5",
                                         font=('Microsoft YaHei UI', 9),
                                         lmargin1=30, lmargin2=30, rmargin=30,
                                         spacing1=3, spacing3=3)
    
    def _format_time_ago(self, timestamp_str: str) -> str:
        """格式化时间为相对时间"""
        try:
            timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
            now = datetime.now()
            diff = now - timestamp
            
            if diff.days > 0:
                return f"{diff.days}天前"
            elif diff.seconds > 3600:
                hours = diff.seconds // 3600
                return f"{hours}小时前"
            elif diff.seconds > 60:
                minutes = diff.seconds // 60
                return f"{minutes}分钟前"
            else:
                return "刚刚"
        except:
            return timestamp_str
    
    def _calculate_conversation_duration(self, messages: List[Dict]) -> str:
        """计算对话持续时间"""
        if len(messages) < 2:
            return "0分钟"
        
        try:
            timestamps = [msg.get('timestamp', '') for msg in messages if msg.get('timestamp')]
            if len(timestamps) < 2:
                return "0分钟"
            
            start_time = datetime.strptime(timestamps[0], "%Y-%m-%d %H:%M:%S")
            end_time = datetime.strptime(timestamps[-1], "%Y-%m-%d %H:%M:%S")
            duration = end_time - start_time
            
            if duration.seconds > 3600:
                hours = duration.seconds // 3600
                minutes = (duration.seconds % 3600) // 60
                return f"{hours}h{minutes}m"
            elif duration.seconds > 60:
                minutes = duration.seconds // 60
                return f"{minutes}分钟"
            else:
                return "1分钟"
        except:
            return "未知"
    
    def _on_search_change(self, *args):
        """搜索框内容变化事件"""
        search_text = self.search_var.get().lower()
        self._filter_history(search_text)
    
    def _filter_history(self, search_text: str):
        """过滤历史记录"""
        if not search_text:
            self.filtered_data = self.history_data.copy()
        else:
            self.filtered_data = []
            for record in self.history_data:
                # 搜索标题
                if search_text in record.get('title', '').lower():
                    self.filtered_data.append(record)
                    continue
                
                # 搜索消息内容
                messages = record.get('messages', [])
                for message in messages:
                    if search_text in message.get('content', '').lower():
                        self.filtered_data.append(record)
                        break
        
        self._update_tree_display()
    
    def _update_tree_display(self):
        """更新树形视图显示"""
        # 清空现有项目
        for item in self.history_tree.get_children():
            self.history_tree.delete(item)
        
        # 填充过滤后的数据
        for i, record in enumerate(self.filtered_data):
            time_str = record.get('timestamp', '未知时间')
            time_ago = self._format_time_ago(time_str)
            title = record.get('title', f'对话 {i+1}')
            messages = record.get('messages', [])
            message_count = len(messages)
            duration = self._calculate_conversation_duration(messages)
            
            # 截断过长的标题
            if len(title) > 25:
                title = title[:22] + "..."
            
            self.history_tree.insert('', 'end', values=(time_ago, title, message_count, duration))
    
    def _clear_search(self):
        """清空搜索"""
        self.search_var.set("")
    
    def _on_double_click(self, event):
        """双击事件 - 直接加载对话"""
        self._on_load_click()
    
    def refresh_history(self):
        """刷新历史记录列表"""
        # 加载历史记录
        self.load_history_data()
        
        # 重置过滤
        self.filtered_data = self.history_data.copy()
        
        # 更新显示
        self._update_tree_display()
    
    def load_history_data(self):
        """从文件加载历史记录数据"""
        history_file = 'chat_history.json'
        
        if os.path.exists(history_file):
            try:
                with open(history_file, 'r', encoding='utf-8') as f:
                    self.history_data = json.load(f)
                # 按时间倒序排列（最新的在前面）
                self.history_data.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
            except (json.JSONDecodeError, FileNotFoundError):
                self.history_data = []
        else:
            self.history_data = []
    
    def update_history_display(self, messages: List[Dict]):
        """更新历史记录显示"""
        if not self.history_display:
            return
        
        self.history_display.config(state=tk.NORMAL)
        self.history_display.delete(1.0, tk.END)
        
        # 更新统计信息
        user_count = sum(1 for msg in messages if msg.get('role') == 'user')
        ai_count = sum(1 for msg in messages if msg.get('role') == 'assistant')
        self.stats_label.config(text=f"用户消息: {user_count} | AI回复: {ai_count}")
        
        for i, message in enumerate(messages):
            role = message.get('role', 'unknown')
            content = message.get('content', '')
            timestamp = message.get('timestamp', '')
            thinking = message.get('thinking', '')
            
            # 添加消息间隔
            if i > 0:
                self.history_display.insert(tk.END, "\n" + "─" * 60 + "\n", "separator")
            
            # 添加时间戳
            if timestamp:
                formatted_time = self._format_display_time(timestamp)
                self.history_display.insert(tk.END, f"⏰ {formatted_time}\n", "timestamp")
            
            # 根据角色添加消息
            if role == 'user':
                self._add_message_bubble("👤 用户", content, "user_header", "user_content")
            elif role == 'assistant':
                # 如果有思考过程，先显示思考
                if thinking:
                    self._add_message_bubble("🧠 AI思考过程", thinking, "thinking_header", "thinking_content")
                    self.history_display.insert(tk.END, "\n")
                
                self._add_message_bubble("🤖 AI助手", content, "ai_header", "ai_content")
            elif role == 'system':
                self._add_message_bubble("⚙️ 系统", content, "system_header", "system_content")
            
            self.history_display.insert(tk.END, "\n")
        
        self.history_display.config(state=tk.DISABLED)
        self.history_display.see(tk.END)
    
    def _format_display_time(self, timestamp_str: str) -> str:
        """格式化显示时间"""
        try:
            timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
            return timestamp.strftime("%m月%d日 %H:%M:%S")
        except:
            return timestamp_str
    
    def _add_message_bubble(self, header: str, content: str, header_tag: str, content_tag: str):
        """添加消息气泡"""
        # 添加消息头部
        self.history_display.insert(tk.END, f" {header} ", header_tag)
        self.history_display.insert(tk.END, "\n")
        
        # 添加消息内容
        if content:
            # 处理长文本的换行
            formatted_content = self._format_content(content)
            self.history_display.insert(tk.END, formatted_content, content_tag)
        
        self.history_display.insert(tk.END, "\n")
    
    def _format_content(self, content: str) -> str:
        """格式化消息内容"""
        # 确保内容不会过长，适当换行
        lines = content.split('\n')
        formatted_lines = []
        
        for line in lines:
            if len(line) > 80:
                # 对于过长的行，尝试在合适的位置换行
                words = line.split(' ')
                current_line = ""
                for word in words:
                    if len(current_line + word) > 80:
                        if current_line:
                            formatted_lines.append(current_line.strip())
                            current_line = word + " "
                        else:
                            formatted_lines.append(word)
                            current_line = ""
                    else:
                        current_line += word + " "
                if current_line:
                    formatted_lines.append(current_line.strip())
            else:
                formatted_lines.append(line)
        
        return '\n'.join(formatted_lines)
    
    def get_selected_conversation(self) -> Dict:
        """获取选中的对话"""
        selection = self.history_tree.selection()
        if not selection:
            return {}
        
        item = selection[0]
        index = self.history_tree.index(item)
        
        if 0 <= index < len(self.filtered_data):
            return self.filtered_data[index]
        
        return {}
    
    def delete_selected_conversation(self):
        """删除选中的对话"""
        conversation = self.get_selected_conversation()
        if not conversation:
            return False
        
        # 确认删除
        result = messagebox.askyesno("确认删除", 
                                   f"确定要删除对话 \"{conversation.get('title', '未知对话')}\" 吗？\n此操作不可撤销。")
        if not result:
            return False
        
        # 从原始数据中找到并删除
        for i, record in enumerate(self.history_data):
            if record.get('timestamp') == conversation.get('timestamp') and record.get('title') == conversation.get('title'):
                del self.history_data[i]
                break
        
        # 保存到文件
        self.save_history_data()
        
        # 刷新显示
        self.refresh_history()
        
        # 清空预览
        if self.history_display:
            self.history_display.config(state=tk.NORMAL)
            self.history_display.delete(1.0, tk.END)
            self.history_display.config(state=tk.DISABLED)
            self.stats_label.config(text="")
        
        return True
    
    def save_history_data(self):
        """保存历史记录数据到文件"""
        history_file = 'chat_history.json'
        try:
            with open(history_file, 'w', encoding='utf-8') as f:
                json.dump(self.history_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存历史记录失败: {e}")
    
    def add_conversation(self, title: str, messages: List[Dict]):
        """添加新的对话到历史记录"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        conversation = {
            'timestamp': timestamp,
            'title': title,
            'messages': messages
        }
        
        # 添加到数据列表开头（最新的在前面）
        self.history_data.insert(0, conversation)
        
        # 保存到文件
        self.save_history_data()
        
        # 刷新显示
        self.refresh_history()
    
    def _on_history_select(self, event):
        """历史记录选择事件"""
        conversation = self.get_selected_conversation()
        if conversation:
            messages = conversation.get('messages', [])
            self.update_history_display(messages)
    
    def _on_load_click(self):
        """加载对话按钮点击事件"""
        conversation = self.get_selected_conversation()
        if conversation and self.on_load_conversation:
            self.on_load_conversation(conversation)
    
    def _on_delete_click(self):
        """删除对话按钮点击事件"""
        if self.delete_selected_conversation() and self.on_delete_conversation:
            self.on_delete_conversation()
    
    def set_callbacks(self, on_load_conversation: Callable = None, on_delete_conversation: Callable = None):
        """设置回调函数"""
        self.on_load_conversation = on_load_conversation
        self.on_delete_conversation = on_delete_conversation
    
    def set_history_data(self, history_data):
        """设置历史数据"""
        self.history_data = history_data if history_data else []
        self.filtered_data = self.history_data.copy()
        self._update_tree_display()